package com.example.security;

import cn.hutool.core.util.StrUtil;
import com.example.entity.SysUser;
import com.example.service.SysUserService;
import com.example.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义Jwt认证过滤器
 */

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取Jwt
        String jwt = request.getHeader(jwtUtils.getHeader());

        if(StrUtil.isBlankOrUndefined(jwt)) {                   //判断jwt是否为空
            chain.doFilter(request,response);                   //如果为空则放行(后面由拦截器判断是否为白名单)
            return;
        }

        Claims claim = jwtUtils.getClaimByToken(jwt);          //调用jwtUtils工具类解析jwt

        if(claim == null) {                                    //判断解析过后的jwt是否为空
            throw new JwtException("token 异常");
        }

        if(jwtUtils.isTokenExpired(claim)) {                    //判断解析过后的jwt是否过期
            throw new JwtException("token 过期");
        }

        String username = claim.getSubject();                  //拿到jwt的主体Subject

        SysUser sysUser = sysUserService.getByUsername(username);

        //获取用户的权限信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,null,userDetailsService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(token);     //设置认证主体，完成自动登录

        chain.doFilter(request,response);           //放行

    }
}
